// pages/customerService/customerService.js
import {baseURL} from '../../utils/request';
let SocketTask = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    socketTaskId: null, //socketId 
    chatList: [],
    inputVal: "",
    baseURL:baseURL,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const token = wx.getStorageSync('userInfo').token
    SocketTask = wx.connectSocket({
      url: 'ws://localhost:8080/chat?token=' + token,
      success: (res) => {
        this.data.socketTaskId = res.socketTaskId
      },
      fail(err) {

      }
    });
    console.log(SocketTask)
    SocketTask.onOpen(res => {
      console.log('------------->socket连接成功，开始会话')
      SocketTask.onMessage(res => {
        if (res.data && SocketTask.OPEN==1) {
          console.log(res.data.split(":"),"会话数据")   
          this.data.chatList.push({
            id: res.data?.split(":")[0],
            chatData: res.data?.split(":")[2],
            url: "",
            name: "客服"
          })
          console.log(this.data.chatList,"chatList")
          this.setData({
            toView:`item${(this.data.chatList.length-1)}`,
            chatList: this.data.chatList
          })
        } else {
          wx.showModal({
            title: '系统提示',
            content: '暂无客服为您服务,很抱歉！',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) wx.navigateBack()
            }
          })
        }
      })
    });
    SocketTask.onClose((res)=>{
      console.log("---------------->对话正常关闭")
    })
    SocketTask.onError(err => {
      wx.showModal({
        title: '系统提示',
        content: '客服系统连接失败',
        showCancel: false,
        complete: (res) => {
          if (res.confirm) wx.navigateBack()
        }
      })
    })
  },
  sendMessage(e) {
    let deptName = wx.getStorageSync('userInfo').deptName
    let imageUrl = wx.getStorageSync('userInfo').imageUrl
    let deptUrl = imageUrl ? `${baseURL}${imageUrl}` : ""
    console.log(deptUrl,"789")
    SocketTask.send({
      data: `1:${e.detail.value.message}`,
      success: (res) => {
        this.data.chatList.push({
          id: 2,
          chatData: e.detail.value.message,
          url: deptUrl,
          name: deptName
        })
        this.setData({
          chatList: this.data.chatList,
          toView:`item${(this.data.chatList.length-1)}`,
          inputVal: ""
        })
      }
    })
  },
  

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let chatData=wx.getStorageSync("chatData")||[];
    this.setData({
      chatList:chatData
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    //小程序后台存储聊天
    console.log("onhide")
    wx.setStorageSync('chatData', this.data.chatList||[])
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //返回页面 存储聊天数据
    console.log("unload")
    wx.setStorageSync('chatData', this.data.chatList||[]);
    SocketTask.close({code:1000})
  },

})